package com.zcsy.manage.web.mall;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.AdCategory;
import com.zcsy.manage.model.mall.AdInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.IAdCategoryService;
import com.zcsy.manage.service.mall.IAdInfoService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * 
 * @Title: AdInfoController.java
 * @Package： com.zcsy.manage.web.mall 
 * @Description: 广告信息控制层
 *
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "adInfo")
public class AdInfoController {
	
	@Autowired
	private IAdInfoService adInfoService;
	
	@Autowired
	private IAdCategoryService adCategoryService;

	@Autowired
	private IDictService dictService;
	
	@Autowired
	private IShopInfoService shopInfoService;
	
	/**新注册 */
	private static final int STATE_NEW          =  1; 
	/**正常 */
	private static final int STATE_SUCCESS      =  2;  
	/**系统禁用*/
	private static final int STAET_FORBIDEN     =  3;  
	/**商户禁用*/
	private static final int STAET_FORBID     =  5; 
	/**未通过审核 */
	private static final int STATE_UNAPPROVED   =  4;  
	/**商户*/
	private static final int TYPE_BUSINESS  =  2; 
	/**平台*/
	private static final int TYPE_PLATFORM  =  1; 
	
	/**
	 * @Description 返回广告位申请列表页面<br>
	 * @param model
	 * @param pNo 当前页
	 * @param userAccount 发布账号
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年4月20日
	 * @see
	 */
	@RequestMapping(value ="/adApply", method = RequestMethod.GET)
	public String adApply(Model model, Integer pNo, Integer pSize, String userAccount, String adCategoryId,HttpServletRequest req){
		
		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);
		
		AdInfo adInfo = new AdInfo();
		if(StringUtils.isNotEmpty(userAccount)){
			adInfo.setUserAccount(userAccount);
		};
		if(StringUtils.isNotEmpty(adCategoryId)){
			adInfo.setAdCategoryId(adCategoryId);
		}
		adInfo.setUserAccountType(TYPE_BUSINESS);
		adInfo.setState(STATE_NEW);
		
		List<AdInfo> adInfos = adInfoService.selectApplyByKeyword(adInfo);
		List<AdCategory> adCategorys = adCategoryService.getAllAdCategory();
		PageInfo<AdInfo> info = new PageInfo<AdInfo>(adInfos);
		
		model.addAttribute("adInfo", info);
		model.addAttribute("adCategorys", adCategorys);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("userAccount", userAccount);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "mall/adinfo/adApply";
	}
	
	/**
	 * 
	 * @Description 返回广告位信息列表页面<br>
	 * 
	 * @param model
	 * @param pNo 当前页
	 * @param title 标题
	 * @param adCategoryId 广告位类型id
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年4月21日
	 * @see
	 */
	@RequestMapping(value ="/adInfoList", method = RequestMethod.GET)
	public String adInfoList(Model model, Integer pNo, Integer pSize, String title, String adCategoryId, HttpServletRequest req){
		
		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);
		
		AdInfo adInfo = new AdInfo();
		
		if(StringUtils.isNotEmpty(title)){
			adInfo.setTitle(title);
		};
		if(StringUtils.isNotEmpty(adCategoryId)){
			adInfo.setAdCategoryId(adCategoryId);
		}
		
		List<AdInfo> adInfos = adInfoService.selectByKeyword(adInfo);
		PageInfo<AdInfo> info = new PageInfo<AdInfo>(adInfos);
		List<AdCategory> adCategorys = adCategoryService.getAllAdCategory();
		
		model.addAttribute("adCategorys", adCategorys);
		model.addAttribute("adInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("title", title);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "mall/adinfo/adInfoList";
	}
	
	/**
	 * @Description 更改发布账号状态<br>
	 * @param model
	 * @param id 主键id
	 * @param state 1新申请 2正常 3禁用 4已拒绝
	 * @author lilan 1063972142@qq.com
	 * @date 2016年4月21日
	 * @see
	 */
	 @RequestMapping(value= "/adApplyUpdate", method = RequestMethod.POST)
	 @ResponseBody
	 public RequestJson adApplyUpdate(Model model, String id, int state, HttpServletRequest request){
			 RequestJson result = new RequestJson();
			 User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
			 int temp = 0;
			 try {
				 AdInfo adInfo = new AdInfo();
				 adInfo.setId(id);
				 switch (state) {
				 case STATE_NEW:
					 temp = STATE_UNAPPROVED;
					 break;
				 case STATE_UNAPPROVED:
					 temp = STATE_NEW;
					 break;
				 case STATE_SUCCESS:
					 temp = STAET_FORBIDEN;
					 break;
				 case STAET_FORBIDEN:
					 temp = STATE_SUCCESS;
					 break;
				 case STAET_FORBID:
					 temp = STATE_SUCCESS;
					 break;
				 default:
					 temp = STATE_SUCCESS;
					 break;
				 }
				 adInfo.setState(temp);
				 adInfoService.update(adInfo);
				 LogUtils.insertLog("用户更新广告位发布账号状态", user.getId(), request);
			 } catch (Exception e) {
				 result.setSuccess(false);
			 }
			 
			return result;
		}
	 
	 /**
	  * @Description 返回广告位信息编辑页面<br>
	  * @param model
	  * @param id 主键ID
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月22日
	  * @see
	  */
	@RequestMapping(value = "editAdInfo", method = RequestMethod.GET)
	public String selectById(Model model, String id, HttpServletRequest req) {
		
	 	//获取当前小区id
	    User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
	    String cellId = user.getCurrentCell().getId();
	    
		 try {
	         if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
	             model.addAttribute("type", Constants.SAVE_TYPE);
	         } else {
	             AdInfo adInfo = adInfoService.selectByPrimaryKey(id);
	             if(adInfo != null){
	            	model.addAttribute("type", Constants.EDIT_TYPE);
	             	model.addAttribute("adInfo", adInfo);
	             	model.addAttribute("adCategoryId", adInfo.getAdCategoryId());
	             }
	         }
	         List<AdCategory> adCategorys = adCategoryService.getAllAdCategory();
			 model.addAttribute("adCategorys",adCategorys);
			 
			 List<ShopInfo> shopInfos = shopInfoService.getStoreByCellId(cellId);
			 model.addAttribute("shopInfos",shopInfos);
	         
	     } catch (Exception e) {
	    	 e.printStackTrace();
	     }
		 
	     return "mall/adinfo/adInfoEdit";
	}
	 
	 /**
	  * @Description 保存和更新广告位信息方法<br>
	  *  id不为空且不为0，则表示更新
      * 否则表示保存
	  * @param title 标题
	  * @param id 主键ID
	  * @param adCategoryId 广告位类型ID
	  * @param beginTime 开始时间
	  * @param endTime 结束时间
	  * @param img 广告图片
	  * @param objType 对象类型 1店铺，2商品，3特殊网页
	  * @param webUrl 网页地址
	  * @param remark 备注说明
	  * @param state 状态
	  * @param userAccount 发布账号
	  * @param userAccountType 账号类型 1新申请，2正常，3禁用，4审核未通过
	  * @param memo 备注
	  * @param sort 排序
	  * @param req 用户请求
	  * @return 
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月22日
	  * @see
	  */
	 @RequestMapping(value="saveOrUpdateAdInfo" , method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson saveOrUpdateAdInfo(String title,String id,String adCategoryId,String beginTime,String endTime,Integer objType,
	    		String objId, String webUrl,String remark,Integer sort,String img,HttpServletRequest request){
	        RequestJson result = new RequestJson();
	        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
	        
	        AdInfo adInfo = new AdInfo();
	        adInfo.setTitle(title);
	        adInfo.setAdCategoryId(adCategoryId);
	        adInfo.setBeginTime(beginTime);
	        adInfo.setEndTime(endTime);
	        adInfo.setObjType(objType);
	        adInfo.setObjId(objId);
	        adInfo.setUrl(webUrl);
	        adInfo.setRemark(remark);
	        adInfo.setSort(sort);
	        adInfo.setImg(img);
	        adInfo.setState(STATE_SUCCESS);
	        adInfo.setUserAccountType(TYPE_PLATFORM);
			adInfo.setUserAccount(user.getLoginname());
	        //adInfo.setMemo(memo);
	        
	        try {
	            if(id != ""&& !"0".equals(id)){
	                adInfo.setId(id);
	                adInfo.setUpdateTime(new Date());
	            	adInfoService.update(adInfo);
	            	LogUtils.insertLog("用户编辑广告位信息", user.getId(), request);
	            }else{
	            	adInfo.setId(UniqueNumberUtils.get18UniqueNumber());
	            	adInfo.setCreateTime(new Date());
	                adInfo.setUpdateTime(new Date());
	            	adInfoService.insert(adInfo);
	            	LogUtils.insertLog("用户新增广告位信息", user.getId(), request);
	            }
	            result.setSuccess(true);
	        } catch (Exception e) {
	            result.setMsg("操作失败");
	        }
	        
	        return result;
	    }
	    
	 /**
	  * @Description 根据主键id删除广告位信息记录<br>
	  * @param ids 广告位信息对象id数组
	  * @param req 用户请求
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月21日
	  * @see
	  */
	    @RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson deleteByPrimaryKey(String ids, HttpServletRequest request){
	    	RequestJson result = new RequestJson();
	    	User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
	    	 try {
	 			String keys[] = ids.split("\\,");
	 			for (int i = 0; i < keys.length; i++ ) {
	 			    adInfoService.deleteByPrimaryKey(keys[i]);
	 			}
	 			LogUtils.insertLog("用户删除广告位信息", user.getId(), request);
	 			result.setSuccess(true);
	 		} catch (NumberFormatException e) {
	 	        result.setSuccess(false);
	 	        result.setMsg("操作失败");
	 		}
	    	 
	         return result;
	     }
	    
	    
		/**
		 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
		 * @param id 商品id
		 * @param req 用户请求
		 * @author caiyinli 13277030520@163.com
		 * @date 2016年6月3日
		 * @see 
		 */
		@RequestMapping(value="updateSort" , method = RequestMethod.GET)
		@ResponseBody
	    public RequestJson updateSort( String id,HttpServletRequest request){
	        RequestJson result = new RequestJson();
	        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	        try {
	        	AdInfo adInfo = adInfoService.selectByPrimaryKey(id);
	        	if(adInfo != null){
	        		adInfo.setUpdateTime(DateUtils.getDate());
	        		adInfoService.updateSort(adInfo);
	        		LogUtils.insertLog("用户置顶广告位信息", user.getId(), request);

	        	}
	        } catch (Exception e) {
	            result.setMsg("操作失败");
	            result.setSuccess(false);
	        }
	       
	        return result;
	    }	    
		/**
		 * @description 广告位申请
		 * @param id 广告位主键id
		 * @param state 广告位状态
		 * @author chenxin
		 * @date 2016年8月23日下午3:52:50
		 */
		@RequestMapping(value= "/adApplyUpdating", method = RequestMethod.POST)
	     @ResponseBody
	     public RequestJson adApplyUpdating(Model model, String id, int state, HttpServletRequest request){
	             RequestJson result = new RequestJson();
	             User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	             int temp = 0;
	             try {
	                 AdInfo adInfo = new AdInfo();
	                 adInfo.setId(id);
	                 switch (state) {
	                 case STATE_UNAPPROVED:
	                     temp = STATE_UNAPPROVED;
	                     break;
	                 case STATE_SUCCESS:
	                     temp = STATE_SUCCESS;
	                     break;
	                 default:
	                     temp = STATE_UNAPPROVED;
	                     break;
	                 }
	                 adInfo.setState(temp);
	                 adInfoService.update(adInfo);
	                 result.setSuccess(true);
	                 LogUtils.insertLog("用户编辑广告位申请信息", user.getId(), request);

	             } catch (Exception e) {
	                 result.setSuccess(false);
	             }
	            return result;
	        }
}